<template>
  <div class="law-dashboard">
    <!-- 用户资料卡片 -->
    <div class="profile-card">
      <div class="profile-header">
        <van-image
          round
          width="80px"
          height="80px"
          :src="avatar"
          class="profile-avatar"
        />
        <div class="profile-info">
          <h2 class="username">{{ username }}</h2>
          <p class="job-title">AI法律助手</p>
        </div>
        <van-icon name="setting" class="settings-icon" size="20px" />
      </div>

      <!-- 统计数据 -->
      <div class="stats-section">
        <div class="stat-item">
          <p class="stat-value">{{ consultationCount }}</p>
          <p class="stat-label">答题总数</p>
          <div class="stat-icon">
            <van-icon name="comment-o" size="18px" />
          </div>
        </div>
        <div class="stat-item">
          <p class="stat-value">{{ correctAnswers }}</p>
          <p class="stat-label">正确回答</p>
          <div class="stat-icon">
            <van-icon name="passed" size="18px" />
          </div>
        </div>
        <div class="stat-item">
          <p class="stat-value">{{ totalPoints }}</p>
          <p class="stat-label">答题积分</p>
          <div class="stat-icon">
            <van-icon name="gold-coin" size="18px" />
          </div>
        </div>
        <!-- 新增的三个统计项 -->
        <div class="stat-item">
          <p class="stat-value">{{ highestScore }}</p>
          <p class="stat-label">最高得分</p>
          <div class="stat-icon">
            <van-icon name="notes-o" size="18px" />
          </div>
        </div>
        <div class="stat-item">
          <p class="stat-value">{{ averageScore }}</p>
          <p class="stat-label">平均得分</p>
          <div class="stat-icon">
            <van-icon name="chart-trending-o" size="18px" />
          </div>
        </div>
        <div class="stat-item">
          <p class="stat-value">{{ honorTitle }}</p>
          <p class="stat-label">荣誉称号</p>
          <div class="stat-icon">
            <van-icon name="medal-o" size="18px" />
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <van-button type="primary" plain block size="small" @click="viewAnswerHistory" class="action-btn">
          <van-icon name="notes-o" size="16px" />
          答题记录
        </van-button>
        <van-button type="info" block size="small" @click="startNewChat" class="action-btn">
          <van-icon name="chat-o" size="16px" class="answer" />
          <span class="anser-text">问答练习</span>
        </van-button>
      </div>
    </div>

    <!-- 最近答题 -->
    <div class="recent-questions">
      <div class="section-header">
        <h3 class="section-title">最近答题</h3>
        <van-button type="default" size="mini" plain @click="viewAllQuestions">
          查看全部
        </van-button>
      </div>

      <div class="record-list" v-if="recentRecords.length > 0">
        <div class="record-card" v-for="record in recentRecords" :key="record.recordNo"
          @click="viewRecordDetails(record.recordNo)">
          <div class="record-header">
            <div class="record-meta">
              <van-tag round :color="getCategoryColor(record.categoryName)" text-color="#fff">
                {{ record.categoryName }}
              </van-tag>
              <span class="record-date">{{ formatDate(record.startTime) }}</span>
            </div>
            <div class="record-score">
              <span class="score-value">{{ record.score }}分</span>
              <div class="score-stars">
                <van-rate :model-value="record.score / 20" allow-half readonly :size="14" color="#ffd21e"
                  void-icon="star" void-color="#eee" />
              </div>
            </div>
          </div>

          <div class="record-progress">
            <div class="progress-info">
              <span>正确率: {{ calculateCorrectRate(record) }}%</span>
              <span>用时: {{ formatDuration(Number(record.duration)) }}</span>
            </div>
            <van-progress :percentage="calculateCorrectRate(record)" stroke-width="6" :show-pivot="false"
              :color="getProgressColor(calculateCorrectRate(record))" />
          </div>

          <div class="correct-count">
            <span>答对 {{ record.correctCount }} 题 / 共 {{ record.totalQuestions }} 题</span>
          </div>
        </div>
      </div>

      <van-empty v-else description="暂无答题记录，开始您的第一次法律问答吧！" image-size="120px">
        <van-button round type="info" size="small" @click="startNewQuestion">
          立即测试
        </van-button>
      </van-empty>
    </div>

    <!-- 法律知识卡片 -->
    <div class="law-tips">
      <div class="section-header">
        <h3 class="section-title">法律小贴士</h3>
        <van-button type="default" size="mini" plain @click="viewMoreTips">
          更多知识
        </van-button>
      </div>

      <van-swipe :loop="false" :width="280" :show-indicators="false">
        <van-swipe-item v-for="tip in lawTips" :key="tip.id">
          <div class="tip-card">
            <h4 class="tip-title">{{ tip.title }}</h4>
            <p class="tip-content">{{ tip.content }}</p>
            <div class="tip-footer">
              <span class="tip-tag">{{ tip.tag }}</span>
              <van-icon name="arrow" size="12px" color="#969799" />
            </div>
          </div>
        </van-swipe-item>
      </van-swipe>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useRouter } from 'vue-router';
import 'vant/lib/index.css';
import { getPracticeHistoryList } from '@/api/record';

const router = useRouter();

// 用户信息
const username = ref("未知用户");
const avatar = ref('');

// 数据状态
const recordsList = ref<Array<any>>([]);
const loading = ref(false);
const error = ref(null);

// 分类数据
const categoriesList = [
  { categoryNo: 'CAT001', categoryName: '民法', color: '#7232dd' },
  { categoryNo: 'CAT002', categoryName: '刑法', color: '#ee0a24' },
  { categoryNo: 'CAT003', categoryName: '行政法', color: '#1989fa' },
  { categoryNo: 'CAT004', categoryName: '宪法', color: '#ff976a' },
  { categoryNo: 'CAT005', categoryName: '经济法', color: '#07c160' }
];

// 法律小贴士
const lawTips = ref([
  {
    id: 1,
    title: "劳动合同解除须知",
    content: "用人单位单方解除劳动合同需提前30日书面通知或支付一个月工资作为代通知金...",
    tag: "劳动法"
  },
  {
    id: 2,
    title: "交通事故责任划分",
    content: "公安机关交通管理部门应当根据交通事故现场勘验、检查、调查情况和有关的检验...",
    tag: "交通法"
  },
  {
    id: 3,
    title: "民间借贷利率上限",
    content: "借贷双方约定的利率超过合同成立时一年期贷款市场报价利率四倍的，超出部分的利息约定无效...",
    tag: "民法"
  }
]);

/**
 * 用户资料卡片的内容模块
 * 
 */
// 统计数据计算
// 计算属性 - 总练习次数
const consultationCount = computed(() => {
  return recordsList.value.reduce((sum, record) => sum + record.totalQuestions, 0);
});
// 计算属性 - 总正确数
const correctAnswers = computed(() => {
  return recordsList.value.reduce((sum, record) => sum + record.correctCount, 0);
});

// 计算属性 - 总答题积分，只有答对超过80分的题目才计分，每次积10分
const totalPoints = computed(() => {
  return recordsList.value
    .filter(record => record.score >= 80)
    .length * 10;
});

// 计算属性 - 最高得分
const highestScore = computed(() => {
  if (recordsList.value.length === 0) return 0;
  return Math.max(...recordsList.value.map(record => record.score));
});

// 计算属性 - 平均得分
const averageScore = computed(() => {
  if (recordsList.value.length === 0) return 0;
  const total = recordsList.value.reduce((sum, record) => sum + record.score, 0);
  return Math.round(total / recordsList.value.length);
});

// 计算属性 - 荣誉称号
const honorTitle = computed(() => {
  const point = totalPoints.value;
  if (point >= 100) return '王者';
  if (point >= 70) return '钻石';
  if (point >= 50) return '黄金';
  if (point >= 30) return '白银';
  if (point >= 20) return '青铜';
  return '新秀';
});



// 计算属性 - 最近4条记录
const recentRecords = computed(() => {
  return [...recordsList.value]
    .sort((a, b) => new Date(b.startTime) - new Date(a.startTime))
    .slice(0, 4);
});

// 计算正确率
const calculateCorrectRate = (record: any) => {
  return Math.round((record.correctCount / record.totalQuestions) * 100);
};

// 计算进度条颜色
const getCategoryColor = (categoryName: string) => {
  const category = categoriesList.find(c => c.categoryName === categoryName);
  return category ? category.color : '#66d8d1';
};

// 计算进度条颜色
const getProgressColor = (percentage: number) => {
  if (percentage >= 80) return '#07c160';
  if (percentage >= 60) return '#ff976a';
  return '#ee0a24';
};

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return `${month}月${day}日`;
};



/**
 * 根据用户编号 获取用户的所有刷题历史记录列表
 * 
 */
const fetchPracticeHistory = async () => {
  try {
    loading.value = true;
    // 从本地存储获取userNo，这里假设存储的是userId
    const userNo = localStorage.getItem("userNo") || "";
    if (!userNo) {
      throw new Error("用户未登录");
    }
    const res = await getPracticeHistoryList(userNo);
    console.log("获取练习记录响应:", res);
    if (res.data.code === 200) {
      console.log("获取练习记录成功:", res.data);
      recordsList.value = res.data.data;
    } else {
      throw new Error(res.message || "获取数据失败");
    }
  } catch (err: any) {
    error.value = err.message;
    console.error("获取练习记录失败:", err);
  } finally {
    loading.value = false;
  }
};

/*
 * 其他页面跳转相关的函数
 *
 */

// 辅助函数 - 格式化持续时间
const formatDuration = (seconds: number) => {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins}分${secs}秒`;
};

// 查看更多或者全部记录
const viewAnswerHistory = () => {
  router.push('/record');
};

//跳转到答题页面
const startNewQuestion = () => {
  // 实现开始新问答逻辑
  router.push('/home');
};

// 跳转到ai问答页面
const startNewChat = () => {
  // 实现开始新问答逻辑
  router.push('/ai-chat');
}

// 查看更多或者全部记录
const viewAllQuestions = () => {
  router.push('/record');
};

const viewRecordDetails = (recordNo: string) => {
  console.log("查看记录详情:", recordNo);
  router.push(`/recordDetail/${recordNo}`);
};

const viewMoreTips = () => {
  // 实现查看更多法律知识逻辑
  router.push('/law-tips');
};

onMounted(() => {
  // 从本地存储中获取用户信息
  username.value = localStorage.getItem("username") || "未知用户";
  avatar.value = localStorage.getItem("avatar") || "";
  console.log("用户名:", username.value);
  console.log("头像:", avatar.value);
  

  // 加载练习记录
  fetchPracticeHistory();
});
</script>

<style scoped>
.law-dashboard {
  padding: 16px;
  background-color: #f7f8fa;
  min-height: 100vh;
}

/* 用户资料卡片 */
.profile-card {
  margin-bottom: 20px;
  padding: 24px 20px;
  background: linear-gradient(135deg, #1976D2 0%, #2196F3 100%);
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(26, 58, 143, 0.2);
  position: relative;
  overflow: hidden;
  color: white;
}

.profile-card::before {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  width: 120px;
  height: 120px;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 50%;
  transform: translate(30%, -30%);
}

.profile-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  position: relative;
  z-index: 1;
}

.profile-avatar {
  border: 3px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.profile-info {
  margin-left: 16px;
  flex: 1;
}

.username {
  font-size: 20px;
  margin: 0;
  color: white;
  font-weight: 600;
}

.job-title {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  margin: 4px 0 0;
  background: rgba(255, 255, 255, 0.2);
  padding: 4px 12px;
  border-radius: 12px;
  display: inline-block;
}

.settings-icon {
  color: white;
  padding: 8px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
}

/* 统计数据 */
.stats-section {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  margin-bottom: 20px;
  padding: 16px 0;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  position: relative;
  z-index: 1;
}

.stat-item {
  text-align: center;
  position: relative;
  padding: 0 8px;
}

/* 移除原有的分隔线样式 */
.stat-item:not(:last-child)::after {
  display: none;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: white;
  margin: 0;
}

.stat-label {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.9);
  margin: 4px 0 0;
}

.stat-icon {
  margin-top: 8px;
  color: white;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 12px;
  position: relative;
  z-index: 1;
}

.action-btn {
  border-radius: 8px;
  height: 40px;
  font-weight: 500;
}

.answer {
  color: black;
}

.anser-text {
  color: black;
}

.action-btn .van-icon {
  margin-right: 6px;
  vertical-align: middle;
}

/* 最近答题 */
.recent-questions,
.law-tips {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 16px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

/* 记录卡片样式 */
.record-list {
  margin-top: 8px;
}

.record-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s;
}

.record-card:active {
  transform: scale(0.98);
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.record-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.record-date {
  font-size: 12px;
  color: #969799;
}

.record-score {
  display: flex;
  align-items: center;
  gap: 6px;
}

.score-value {
  font-size: 18px;
  font-weight: bold;
  color: #1989fa;
}

.score-stars {
  display: flex;
  align-items: center;
}

.record-progress {
  margin: 12px 0;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #969799;
  margin-bottom: 6px;
}

.correct-count {
  font-size: 13px;
  color: #666;
  text-align: center;
  padding-top: 8px;
  border-top: 1px dashed #eee;
}

/* 法律小贴士 */
.law-tips {
  padding-bottom: 10px;
}

.tip-card {
  padding: 16px;
  background: #f7f8fa;
  border-radius: 8px;
  height: 120px;
  display: flex;
  flex-direction: column;
}

.tip-title {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #1a3a8f;
}

.tip-content {
  font-size: 13px;
  color: #666;
  flex: 1;
  margin: 0;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.tip-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.tip-tag {
  font-size: 12px;
  color: #1a3a8f;
  background: rgba(26, 58, 143, 0.1);
  padding: 2px 8px;
  border-radius: 10px;
}

/* 空状态 */
.van-empty {
  padding: 30px 0;
}

.van-empty__description {
  margin-top: 16px;
  color: #666;
}

.van-empty .van-button {
  margin-top: 20px;
}
</style>